<template>
  <div class="task-logs">
    <div class="page-header">
      <h2>{{ $t('logs.title') }}</h2>
      <a-button @click="refreshLogs">
        <ReloadOutlined />
        {{ $t('common.refresh') }}
      </a-button>
    </div>

    <div class="filter-bar">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-select
            v-model:value="selectedTask"
            :placeholder="$t('logs.filter.selectTask')"
            style="width: 100%"
            allow-clear
            @change="loadLogs"
          >
            <a-select-option
              v-for="task in tasks"
              :key="task.id"
              :value="task.id"
            >
              {{ task.name }}
            </a-select-option>
          </a-select>
        </a-col>
        <a-col :span="4">
          <a-select
            v-model:value="statusFilter"
            :placeholder="$t('logs.filter.selectStatus')"
            style="width: 100%"
            allow-clear
            @change="loadLogs"
          >
            <a-select-option value="success">{{ $t('logs.status.success') }}</a-select-option>
            <a-select-option value="failed">{{ $t('logs.status.failed') }}</a-select-option>
            <a-select-option value="timeout">{{ $t('logs.status.timeout') }}</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="6">
          <a-range-picker
            v-model:value="dateRange"
            style="width: 100%"
            @change="loadLogs"
          />
        </a-col>
      </a-row>
    </div>

    <a-table
      :columns="columns"
      :data-source="logs"
      :loading="loading"
      row-key="id"
      :pagination="{ pageSize: 20 }"
      :expandable="{ expandedRowRender }"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'taskName'">
          <span v-if="record.taskName">{{ record.taskName }}</span>
          <span v-else style="color: #999; font-style: italic;">{{ $t('logs.messages.unknownTask') }}</span>
        </template>
        <template v-else-if="column.key === 'status'">
          <a-tag :color="getStatusColor(record.status)">
            {{ getStatusText(record.status) }}
          </a-tag>
        </template>
        <template v-else-if="column.key === 'duration'">
          <span v-if="record.duration">{{ record.duration }}{{ $t('logs.duration.ms') }}</span>
          <span v-else>-</span>
        </template>
        <template v-else-if="column.key === 'startTime'">
          {{ formatTime(record.startTime) }}
        </template>
        <template v-else-if="column.key === 'endTime'">
          <span v-if="record.endTime">{{ formatTime(record.endTime) }}</span>
          <span v-else>-</span>
        </template>
        <template v-else-if="column.key === 'actions'">
          <a-button 
            type="link" 
            size="small" 
            @click="viewExecutionResult(record)"
          >
            {{ $t('logs.actions.viewResult') }}
          </a-button>
        </template>
      </template>
    </a-table>

    <!-- 执行结果模态窗口 -->
    <a-modal
      v-model:open="resultModalVisible"
      :title="$t('logs.detail.title')"
      width="800px"
      :footer="null"
      :maskClosable="true"
    >
      <div v-if="currentLogRecord" class="execution-result">
        <!-- 基本信息 -->
        <div class="result-section">
          <h4>{{ $t('logs.detail.basicInfo') }}</h4>
          <a-descriptions :column="2" bordered size="small">
            <a-descriptions-item :label="$t('logs.detail.taskName')">
              {{ currentLogRecord.taskName || $t('logs.messages.unknownTask') }}
            </a-descriptions-item>
            <a-descriptions-item :label="$t('logs.detail.status')">
              <a-tag :color="getStatusColor(currentLogRecord.status)">
                {{ getStatusText(currentLogRecord.status) }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item :label="$t('logs.detail.startTime')">
              {{ formatTime(currentLogRecord.startTime) }}
            </a-descriptions-item>
            <a-descriptions-item :label="$t('logs.detail.endTime')">
              {{ currentLogRecord.endTime ? formatTime(currentLogRecord.endTime) : '-' }}
            </a-descriptions-item>
            <a-descriptions-item :label="$t('logs.detail.duration')">
              {{ currentLogRecord.duration ? `${currentLogRecord.duration}${$t('logs.duration.ms')}` : '-' }}
            </a-descriptions-item>
            <a-descriptions-item :label="$t('logs.detail.exitCode')">
              {{ currentLogRecord.exitCode ?? 'N/A' }}
            </a-descriptions-item>
          </a-descriptions>
        </div>

        <!-- 输出日志 -->
        <div class="result-section">
          <h4>{{ $t('logs.detail.outputLog') }}</h4>
          <div class="log-output-container">
            <pre class="log-output">{{ currentLogRecord.output || $t('logs.messages.noResult') }}</pre>
          </div>
        </div>

        <!-- 错误信息 -->
        <div v-if="currentLogRecord.error" class="result-section">
          <h4>{{ $t('logs.detail.errorInfo') }}</h4>
          <div class="log-error-container">
            <pre class="log-error">{{ currentLogRecord.error }}</pre>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, h, computed } from 'vue'
import { useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { message } from 'ant-design-vue'
import dayjs, { Dayjs } from 'dayjs'
import { ReloadOutlined } from '@ant-design/icons-vue'
import { taskAPI, logAPI } from '@/api'

const { t } = useI18n()
const route = useRoute()

interface Task {
  id: string
  name: string
}

interface LogEntry {
  id: string
  taskId: string
  taskName: string
  status: 'success' | 'failed' | 'timeout' | 'running'
  startTime: string
  endTime?: string
  duration?: number
  output?: string
  error?: string
  exitCode?: number
}

const loading = ref(false)
const selectedTask = ref<string>()
const statusFilter = ref<string>()
const dateRange = ref<[Dayjs, Dayjs]>()
const tasks = ref<Task[]>([])
const logs = ref<LogEntry[]>([])

// 执行结果模态窗口相关状态
const resultModalVisible = ref(false)
const currentLogRecord = ref<LogEntry | null>(null)

const columns = computed(() => [
  {
    title: t('logs.columns.taskName'),
    dataIndex: 'taskName',
    key: 'taskName',
    width: 200
  },
  {
    title: t('logs.columns.status'),
    key: 'status',
    width: 100
  },
  {
    title: t('logs.columns.startTime'),
    key: 'startTime',
    width: 160
  },
  {
    title: t('logs.columns.endTime'),
    key: 'endTime',
    width: 160
  },
  {
    title: t('logs.columns.duration'),
    key: 'duration',
    width: 100
  },
  {
    title: t('logs.columns.actions'),
    key: 'actions',
    width: 120,
    fixed: 'right'
  }
])

const expandedRowRender = (record: LogEntry) => {
  return h('div', { class: 'log-detail' }, [
    h('div', { class: 'log-section' }, [
      h('h4', t('logs.detail.outputLog')),
      h('pre', { class: 'log-output' }, record.output || t('logs.messages.noResult'))
    ]),
    record.error ? h('div', { class: 'log-section' }, [
      h('h4', t('logs.detail.errorInfo')),
      h('pre', { class: 'log-error' }, record.error)
    ]) : null,
    h('div', { class: 'log-meta' }, [
      h('span', `${t('logs.detail.exitCode')}: ${record.exitCode ?? 'N/A'}`)
    ])
  ].filter(Boolean))
}

const getStatusColor = (status: string) => {
  switch (status) {
    case 'success':
      return 'green'
    case 'failed':
      return 'red'
    case 'timeout':
      return 'orange'
    case 'running':
      return 'blue'
    default:
      return 'default'
  }
}

const getStatusText = (status: string) => {
  switch (status) {
    case 'success':
      return t('logs.status.success')
    case 'failed':
      return t('logs.status.failed')
    case 'timeout':
      return t('logs.status.timeout')
    case 'running':
      return t('logs.status.running')
    default:
      return t('logs.status.unknown')
  }
}

const formatTime = (time: string) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

const loadTasks = async () => {
  try {
    const taskList = await taskAPI.getTasks()
    tasks.value = taskList.map(task => ({
      id: task.id,
      name: task.name
    }))
  } catch (error) {
    message.error(t('logs.messages.loadTasksFailed'))
    tasks.value = []
  }
}

const loadLogs = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params: any = {}
    if (selectedTask.value) {
      params.taskId = selectedTask.value
    }
    if (statusFilter.value) {
      params.status = statusFilter.value
    }
    if (dateRange.value && dateRange.value.length === 2) {
      params.startDate = dateRange.value[0].format('YYYY-MM-DD')
      params.endDate = dateRange.value[1].format('YYYY-MM-DD')
    }
    
    // 调用API获取执行日志
    const result = await logAPI.getLogs(params)
    console.log('API返回的日志数据:', result)
    
    // 转换数据格式以匹配LogEntry接口
    logs.value = result.logs.map(log => {
      console.log('处理日志记录:', log)
      return {
        id: log.id.toString(),
        taskId: log.taskId,
        taskName: log.taskName || t('logs.messages.unknownTask'),
        status: log.status === 'error' ? 'failed' as const : 
                log.status === 'stopped' ? 'timeout' as const : 
                log.status as 'success' | 'running',
        startTime: log.startTime,
        endTime: log.endTime,
        duration: log.duration,
        output: log.output,
        error: log.error,
        exitCode: log.exitCode
      }
    })
    console.log('转换后的日志数据:', logs.value)
  } catch (error) {
    message.error(t('logs.messages.loadLogsFailed'))
    logs.value = []
  } finally {
    loading.value = false
  }
}

const refreshLogs = () => {
  loadLogs()
}

const viewExecutionResult = (record: LogEntry) => {
  currentLogRecord.value = record
  resultModalVisible.value = true
}

onMounted(() => {
  loadTasks()
  
  // 如果URL中有taskId参数，自动选择对应的任务
  const taskId = route.query.taskId
  if (taskId) {
    selectedTask.value = taskId as string
  }
  
  loadLogs()
})
</script>

<style lang="less" scoped>
.task-logs {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.filter-bar {
  margin-bottom: 16px;
}

.log-detail {
  background: #f9f9f9;
  padding: 16px;
  border-radius: 4px;
}

.log-section {
  margin-bottom: 16px;
}

.log-section h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #666;
}

.log-output,
.log-error {
  background: #fff;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  padding: 12px;
  margin: 0;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  line-height: 1.4;
  white-space: pre-wrap;
  word-break: break-all;
  max-height: 200px;
  overflow-y: auto;
}

.log-error {
  border-color: #ff4d4f;
  background: #fff2f0;
}

.log-meta {
  font-size: 12px;
  color: #999;
}

.log-meta span {
  margin-right: 16px;
}

/* 执行结果模态窗口样式 */
.execution-result {
  max-height: 70vh;
  overflow-y: auto;
}

.result-section {
  margin-bottom: 24px;
}

.result-section h4 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #262626;
}

.log-output-container,
.log-error-container {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  overflow: hidden;
}

.execution-result .log-output,
.execution-result .log-error {
  background: #fafafa;
  border: none;
  border-radius: 0;
  padding: 16px;
  margin: 0;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 13px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-break: break-all;
  max-height: 300px;
  overflow-y: auto;
}

.execution-result .log-error {
  background: #fff2f0;
  border-color: #ff4d4f;
}

.log-error-container {
  border-color: #ff4d4f;
}
</style> 